/**
 * 
 */
package com.sdkj.jdbc.utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库JDBC连接帮助类
 * @author leiweiping
 * date: 2017-05-10
 */
public class DBHelper {
	
	/**
	 * 创建数据库连接对象
	 */
	public static Connection getCon(){
		//读取配置文件中的数据库配置信息
        Properties prop =  new  Properties();    
        InputStream in = DBHelper.class.getResourceAsStream( "/dbconfig.properties" );
        Connection conn = null;
         try  {    
            prop.load(in);    
            String url = prop.getProperty( "url" ).trim();    
            String driverClassName = prop.getProperty( "driverClassName" ).trim();  
            String userName = prop.getProperty( "username" ).trim();    
            String passWord = prop.getProperty( "password" ).trim();  
            Class.forName(driverClassName);
    		conn = DriverManager.getConnection(url, userName, passWord);
        }  catch  (Exception e) {    
            e.printStackTrace();    
        }
         return conn;   
    } 
	
	/**
	 * 关闭数据库的相关链接
	 * @param rs
	 * 记录集
	 * @param ps
	 * 声明
	 * @param conn
	 * 链接对象
	 */
	public static void close(ResultSet rs, PreparedStatement ps, Connection conn) {
		// 关闭记录集
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		// 关闭声明
		if (ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		// 关闭链接对象
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
